using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;


namespace Kaseya
{
    public class hash
    {
        public bool CheckCoveredPassword(string ClientCoveredPassword, string ServerCoveredPassword, string RandomNumber)
        {
            ServerCoveredPassword = ServerCoveredPassword.Replace("cover", "");
            ServerCoveredPassword = HashValues(ServerCoveredPassword, RandomNumber);
            if (ServerCoveredPassword == ClientCoveredPassword)
                return true;

            return false;
        }

        public string HashToCoveredPassword(string UserName, ref string Password)
        {
            string Rand = GenerateRandomNumber(8);

            Password = HashValues(Password, UserName);
            Password = HashValues(Password, Rand);

            return Rand;
        }

        private string HashValues( string Value1, string Value2)
        {
            SHA1Managed hash = new SHA1Managed();
            byte[] arrByte = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Value1 + Value2));
            string s = "";
            for (int i = 0; i < arrByte.Length; i++)
            {
                s += arrByte[i].ToString("X2").ToLower();
            }
            return s;
        }

        private string GenerateRandomNumber(int NumberOfDigits)
        {
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] numbers = new byte[NumberOfDigits * 2];
            rng.GetNonZeroBytes(numbers);

            string result = "";
            for (int i = 0; i < NumberOfDigits; i++)
            {
                result += numbers[i].ToString();
            }

            result = result.Replace("0", "");
            return result.Substring(1, NumberOfDigits);

        }
    }
        
}
